﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WinSort.Ctrl;
using System.Threading;

namespace WinSort
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var lst = new List<int>();
            var rng = new Random();
            for (int i = 0; i < numericUpDown1.Value; i++)
            {
                lst.Add(rng.Next(10, 200));
            }
            
            //var sort = new BubbleSorter(lst.ToArray(), view1.Draw);
            Start<BubbleSorter>(lst, view1);
            Start<SelectionSorter>(lst, view2);
            Start<ShellSorter>(lst, view3);
            Start<InsertionSorter>(lst, view4);
            Start<QuickSorter>(lst, view5);
            //view1.Draw(lst);
        }

        void Stop()
        {
            foreach (Control item in this.Controls)
            {
                var t = item.Tag as Thread;
                if (t != null)
                    t.Abort();
            }
        }

        Thread Start<T>( List<int> source, Ctrl.View view) where T:BaseSort,new()
        {
            var sorter = new T();
            sorter.action = view.Draw;
            view.Label.Text = sorter.Name;
            sorter.list = source.ToArray();
            
            var thread = new Thread(new ThreadStart(sorter.Sort));
            thread.Start();
            view.Tag = thread;
            return thread;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
            Stop();
        }
    }
}
